<?php

namespace App\Repositories;


use App\Interfaces\GoodsService;
use App\Models\Goods;
use App\Models\GoodsContent;
use App\Models\GoodsGallery;
use App\Models\Category;
use App\Models\Shop;
use App\Models\Address;
use App\Models\ProductSku;
use Config;
//use App\Interfaces\CategoryService;
//use App\Repositories\CategoryRepositories;

class GoodsRepository implements GoodsService{


    /**
     * 获取单个商品
     *
     * @param $goods_id
     *
     * @date 2015/12/21
     * @author Leen
     */
    public function get($goods_id){
    	$goods = Goods::find($goods_id);

        if(!empty($goods)) {
            $goods_id = $goods->goods_id;
            $goodsContent = GoodsContent::find($goods_id);

            if ($goodsContent) {

                $goods_content = $goodsContent->goods_content;

                $mobile_goods_content = $goodsContent->mobile_goods_content;
            } else {

                $goods_content = '';
                $mobile_goods_content = '';
            }//end if()
            $goods['goods_content'] = $goods_content;
            $goods['mobile_goods_content'] = $mobile_goods_content;
        }//end if()
    	return $goods;

    }//end func get()


    public function getGoodsBySn($goods_sn){

        return Goods::where('goods_sn',$goods_sn)->first();

    }

    /**
     * 根据商品id数组获取商品信息
     * @param  [type] $goods_ids [商品id数组]
     * @return [type]            [description]
     */
    public function getGoodsByIds($goods_ids){

        return Goods::whereIn('goods_id', $goods_ids)->get();

    }


    public function getGoodsByShop($shop_id,$page){
        return Goods::where('shop_id',$shop_id)->where('is_on_sale',1)->paginate(8,['*'],'page',$page);
    }

    public function getShopGoods($shop_id){
        return Goods::where('shop_id',$shop_id)->where('is_on_sale',1)->get()->take(8);

    }

    public function countGoodsByShop($shop_id){
        return Goods::where('shop_id',$shop_id)->where('is_on_sale',1)->count();
    }

    /**
     * 根据分类ID获取所有商品
     * @param $cat_id
     * @return mixed
     */
    public function getCatGoods($cat_id,$number=10,$page){

        $category = Category::find($cat_id);

        if ($category){
            $childIds = $category->getChildIds()->push($cat_id)->toArray();
            return Goods::whereIn('cat_id',$childIds)->where('is_on_sale',1)
                ->where('is_delete',0)
                ->orderBy('sort_order','desc')
                ->paginate($number,['*'],'page',$page);

        }else{
            return collect();
        }


    }//end func getCatGoods()


    /**
     * 根据指定标识获取商品,如:首页推荐,分类推荐等..flag 为数据库字段名,如: is_cat_recommend
     * @return mixed
     */
    public function getFlagGoods($cat_id,$flag){

    }//end func getFlagGoods()

    /**
     * 获取分类推荐商品
     * @return mixed
     */
    public function getCatRecommendGoods($cat_id){

    }//end func getCatRecommendGoods()

    /**根据指定ID数组获取商品
     * @param array $ids
     * @return mixed
     */
    public function getByIds($ids = []){

    }//end func getByIds()

    /**
     * 获取商品图集
     * @param $goods_id
     * @return mixed
     */
    public function getGoodsGallery($goods_id){
        $goods = Goods::find($goods_id);

        $goodsGallery = GoodsGallery::select('goods_gallery.*','goods.goods_thumb')
                                    ->join('goods','goods.goods_id','=','goods_gallery.goods_id')
                                    ->where('goods_gallery.goods_id',$goods_id)->get();

        if($goodsGallery->count()){
            //dd($goods->mobile_goods_thumb);
            $goodsGallery[0]->mobile_goods_thumb = $goods->mobile_goods_thumb;
        }

        return $goodsGallery;
    }//end func getGoodsGallery()

    /**
     * 根据商品id获取商品所属商铺信息
     * @param $goods_id
     * @return mixed
     */
    public function getShop($shop_id){
        //$goodsShop = Shop::where('is_show', 0)->find($shop_id);       //只查找要显示的店铺
        $goodsShop = Shop::find($shop_id);

        return $goodsShop;
    }//end func $goodsShop()


    /**
     * 根据商品id获取商品的同类产品
     * @param $goods_id
     * @return mixed
     */
    public function getSimilar($goods_id){
        $goods = Goods::find($goods_id);
        $goods_name = $goods->goods_name;
        $cat_id = $goods->cat_id;

        $categoryGoods = Goods::where('cat_id', $cat_id)->where('is_on_sale', 1)->where('goods_id', '<>', $goods_id)->orderBy('add_time', 'desc')->get();

        $similarGoodsNum = $categoryGoods->count();
        if($similarGoodsNum<4){
            //TODO如果数量不够查找根分类下的商品
            $root_cat_obj = Category::where('parent_id',0)->orderBy('sort_order','desc')->orderBy('cat_id','asc')->get();

            foreach($root_cat_obj as $key=>$value){

                $root_cat_id = $value->cat_id;
                //echo "<BR>root_cat_id:".$root_cat_id;

                $categoryRootGoods = Goods::where('cat_id', $root_cat_id)->where('is_on_sale', 1)->where('goods_id', '<>', $goods_id)->orderBy('add_time', 'desc')->get();

            }//end foreach()

        }//end if()

        return $categoryGoods;
    }//end func getSimilar


    /**
     * 随机获取商品的同类产品
     * @param $goods_count 随机取的条数
     * @return mixed
     */
    public function getRandomGoods($goods_count){
        $goods = Goods::orderByRaw('RAND()')->get()->take($goods_count);
        foreach($goods as $key=>$good){
            $cat_id = $good->cat_id;
            $categoryGoods = Goods::where('cat_id', $cat_id)->where('is_on_sale', 1)->orderBy('add_time', 'desc')->get()->take($goods_count);
            $similarGoodsNum = $categoryGoods->count();

            if($similarGoodsNum>0){
                return $categoryGoods;

            }else{
                return collect();
            }
        }

    }//end func getSimilar


    public function getGoodsShippingFee($type,$address_id,$goodsPrice){
        //E贸易订单免邮费
        if ($type) return 0.0;

        //满60包邮
        if ($goodsPrice>=config('shipping-price.freePostAmount')){

            return 0.00;
        }

        if (intval($address_id)==0){
            return 0.00;
        }


        $config = config('shipping-price');

        $specialArea = $config['specialArea'];
        //新疆西藏15  其他10


        $address = Address::find($address_id);

        if(!$address){
            return $config['postage'];
        }

        if (in_array(str_replace(" ",'',$address->province),$specialArea)){

            return $config['special'];
        }else{
            return $config['postage'];

        }
    }


    public function getDefaultAddress($user_id){
        if(empty($user_id)){

            throw new AddressServiceException("用户的id不能为空");

        }//end if()

        $address = Address::where('user_id', $user_id)->where('is_default', 1)->first();

        //如果没有默认地址，按时间排序将最早的设为默认地址
        if(empty($address)){
            $address = Address::orderBy('address_id', 'asc')->where('user_id', $user_id)->first();
            if($address){
                $address_id = $address->address_id;
                Address::where('address_id', $address_id)->update(['is_default'=>1]);

                $address = Address::where('user_id', $user_id)->where('is_default', 1)->first();
            }

        }//end func

        return $address;
    }

    public function attributValueRedirect($goods_id, array $attributValueArr){

        $skus = $this->getSkus($attributValueArr,$delimiter=',');

        $product_id = ProductSku::where('goods_id', $goods_id)->pluck('product_id');

        $productSkus = ProductSku::where('product_id', $product_id)->get();
        if ($productSkus) {
            foreach ($productSkus as $key => $productSku) {
                $attribute_group = $productSku->attribute_group;

                if(in_array($attribute_group, $skus)){
                    $goods_id = $productSku->goods_id;
                    break;
                }else{
                    continue;
                }
            }//end if()
        }
        return $goods_id;

    }

    public function mobileAttributValueRedirect($goods_id, array $attributValueArr){

        $skus = $this->getSkus($attributValueArr,$delimiter=',');

        $product_id = ProductSku::where('goods_id', $goods_id)->pluck('product_id');

        $productSkus = ProductSku::where('product_id', $product_id)->get();
        if ($productSkus) {
            foreach ($productSkus as $key => $productSku) {
                $attribute_group = $productSku->attribute_group;

                if(in_array($attribute_group, $skus)){
                    $goods_id = $productSku->goods_id;
                    break;
                }else{
                    $goods_id = -1;
                }
            }//end if()
        }
        return $goods_id;

    }

    /**
     * 根据属性数组找到所有的属性组合
     * @param  [type] $arr       [description]
     * @param  string $delimiter [description]
     * @return [type]            [description]
     */
    public function getSkus($arr,$delimiter=','){

        //sku数组
        $skus = [];
        //正向排列
        sort( $arr );
        //获取数组长度
        $len = count ( $arr )-1;
        //记录传入的排列
        $skus[]=implode($delimiter,$arr);
        while (true){
            //从右侧开始找到第一个左侧(A)<右侧(B)的数字序列
            for ( $i = $len ; $i >=0; $i --){
                if ( $arr [ $i ]> @$arr[$i -1]){
                    $here = $i -1;
                    break ;
                }
            }
            //若找到了则开始换位
            if ( $here >=0){
                //从有右向左侧找，第一个比左侧(A)大的数字(C)交换位置得到CBA
                for ( $j = $len ; $j > $here ; $j --){
                    if ( $arr [ $here ]< $arr [ $j ]){
                        $revers = $j ;
                        list( $arr [ $here ], $arr [ $j ]) = array ( $arr [ $j ], $arr [ $here ]);
                        break ;
                    }
                }
                //将后续数字倒序得到CAB
                unset( $newarr );
                for ( $h = $here +1; $h <= $len ; $h ++){
                    $newarr [] = $arr [ $h ];
                    unset( $arr [ $h ]);
                }

                $arr = array_merge ( $arr , array_reverse ( $newarr ,TRUE));
                $skus[]=implode($delimiter,$arr);

            } else {
                break ;
            }
        }
        return $skus ;

    }//end func getSkus



}//end class GoodsRepository